package com.htthorizon.model.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.htthorizon.common.core.web.controller.BaseController;
import com.htthorizon.common.core.web.domain.AjaxResult;
import com.htthorizon.common.core.web.page.TableDataInfo;
import com.htthorizon.common.log.annotation.Log;
import com.htthorizon.common.log.enums.BusinessType;
import com.htthorizon.common.security.annotation.RequiresPermissions;
import com.htthorizon.excel.excel.ModelUseExcel;
import com.htthorizon.model.domain.ModelUse;
import com.htthorizon.model.request.ModelUseSearch;
import com.htthorizon.model.service.IModelUseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author Brilliant
 */
@RestController
@RequestMapping("/modelUse")
public class ModelUseController extends BaseController {

    @Autowired
    private IModelUseService modelUseService;

    @GetMapping("/list")
    @RequiresPermissions("model:stat:index")
    @Log(title = "模型管理/模型使用情况", businessType = BusinessType.QUERY)
    public TableDataInfo list(ModelUseSearch modelUseSearch){
        startPage();
        List<ModelUse> list= modelUseService.list(modelUseSearch);
        return getDataTable(list);
    }

    @PostMapping("/download")
    @RequiresPermissions("model:stat:index")
    @Log(title = "模型管理/模型使用情况导出", businessType = BusinessType.EXPORT)
    public AjaxResult download(HttpServletResponse response) throws IOException {

        List<ModelUseExcel> data =  modelUseService.listAllDownload();

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");

        String format = DateUtil.format(DateUtil.date(), "yyyy-MM-dd");

        String fileName = URLEncoder.encode("模型使用情况", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), ModelUseExcel.class).sheet(format).doWrite(data);
        return success();
    }


}
